// pages/specialSupply/specialSupply.js
const app = getApp()
var util =  require('../../utils/util.js');
var btnFlag = false

Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeColor: app.globalData.themeColor,
    dishesList: [],
    total: 0,
    selectNum: 0,
    maxLength: 100,
    dateType: 0,
    userId: '',
    contentId: '',
    status: null,
    date: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      date: util.setTime(new Date())
    })
    that.getData()
  },

  getData(){
    var that = this
    util.getAjax(app.globalData.apiUrl +'/Api/Food/get_caipu',function(res){
      console.log(res)
      var list = res.data.map((item) => {
        item.isCheck = false
        item.num = 1
        item.isShowDetails = false
        return item
      })
      that.setData({
        dishesList: list
      })
    },{status: 1})
  },
  // 详情隐藏显示
  detailsChange(e){
    const {
      index
    } = e.currentTarget.dataset;
    var that = this
    let list = that.data.dishesList
    list[index].isShowDetails = !list[index].isShowDetails
    that.setData({
      dishesList: list,
    })
  },
  // 菜品选择
  dishesChange(e){
    const {
      index
    } = e.currentTarget.dataset;
    var that = this
    let list = that.data.dishesList
    list[index].isCheck = !list[index].isCheck
    let selectList = list.filter(item => item.isCheck)
    that.setData({
      dishesList: list,
      selectNum: selectList.length
    })
    that.getTotal()
  },
  // 增加
  addClick(e){
    var that = this
    const {
      index
    } = e.currentTarget.dataset;
    let list = that.data.dishesList
    if(list[index].num < that.data.maxLength){
      list[index].num ++ 
      that.setData({
        dishesList: list
      })
      if(list[index].isCheck){
        that.getTotal()
      }
    }
  },
  // 减少
  delClick(e){
    const {
      index
    } = e.currentTarget.dataset;
    var that = this
    let list = that.data.dishesList
    if(list[index].num > 1){
      list[index].num --
      that.setData({
        dishesList: list
      })
      if(list[index].isCheck){
        that.getTotal()
      }
    }
    
  },
  getTotal(){
    var that = this
    let list = that.data.dishesList.filter(item => item.isCheck)
    var total = 0
    for(let i in list){
      if(list[i].isCheck){
        total += Number(list[i].price) * Number(list[i].num)
      }
    }
    that.setData({
      total: total
    })
  },
  
  //订餐按钮
  OrderMealBtn:function(e){
    var that = this
    if(btnFlag){
      return
    }
    btnFlag = true
    if(that.data.dateType == 0){
      util.showToast('未在定餐时间，或请重试','none',2000)
      btnFlag = false
      return;
    }
    var type = e.currentTarget.dataset.type
    if(that.data.status && that.data.status == 1 && that.data.userId && that.data.contentId){
      let selectList = that.data.dishesList.filter(item => item.isCheck)
      var data = []
      for(let i in selectList){
        if(Number(selectList[i].num) > 1){
          for (let j = 0; j < selectList[i].num; j++) {
            let info = {
              name: selectList[i].name
            }
            data.push(info)
          }
        }else{
          let info = {
            name: selectList[i].name
          }
          data.push(info)
        }
      }
      console.log(data)
      data = JSON.stringify(data)

      // console.log(data)
      util.postAjax(app.globalData.apiUrl +'/Api/Food/yes_food_two',function(res){
        console.log(res)
        if(res.data == '1'){
          //成功
          let text = '恭喜您，预定成功'
          util.showToast(text,'none',2000)
          that.getData()
        }else{
          //失败
          util.showModal('提示','订餐失败，请重试')
        }
        btnFlag = false
      },{user_id: that.data.userId,date: that.data.date,pro_two: data})
    }else{
      wx.login({
        success:function(login){
          // 发送请求
          wx.request({
            url: app.globalData.apiUrl + '/Api/GetUser/get_openid', //接口地址
            data: {
              code: login.code,
            },
            method: 'get',
            header: {
              'content-type': 'application/json' //默认值
            },
            success: function (res) {
              console.log(res)
              //判断用户是否存在
              if(res.data.code == '1'){
                app.globalData.userId = res.data.data.id;
                app.globalData.contentId = res.data.data.content_id;
                app.globalData.status = res.data.data.status;
                if(res.data.data.is_manager){
                  app.globalData.isManager = res.data.data.is_manager
                }
                if(res.data.data.status == 1){
                  let selectList = that.data.dishesList.filter(item => item.isCheck)
                  var data = []
                  for(let i in selectList){
                    if(Number(selectList[i].num) > 1){
                      for (let j = 0; j < selectList[i].num -1 ; j++) {
                        data.push({
                          name: selectList[i].name
                        })
                      }
                    }else{
                      data.push({
                        name: selectList[i].name
                      })
                    }
                  }
                  console.log(data)
                  data = JSON.stringify(data)
                  // console.log(data)
                  util.postAjax(app.globalData.apiUrl +'/Api/Food/yes_food',function(res){
                    console.log(res)
                    if(res.data == '1'){
                      //成功
                      that.setData({
                        isOrderMeal: true
                      })
                      let text = '您' + that.getType(type) + '成功'
                      util.showToast(text,'none',2000)
                      that.getData()
                    }else{
                      //失败
                      util.showModal('提示','订餐失败，请重试')
                    }
                    btnFlag = false
                  },{user_id: that.data.userId,date: that.data.date,pro_two: data})
                }else{
                  util.showToast('您还未通过审核，暂不能定餐','none',2000),
                  btnFlag = false
                }
              }
            }
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
   onShow: function () {
    var that = this
    if(app.globalData.mainTime.length != 0){
      let dateType = 0
      for(let i in app.globalData.mainTime){
        let isDate = util.setDate(app.globalData.mainTime[i].food_time,app.globalData.mainTime[i].food_end_time)
        if(isDate){
          dateType = Number(app.globalData.mainTime[i].id)
          break;
        }
      }
      that.setData({
        mainTime: app.globalData.mainTime,
        dateType: Number(dateType)
      })
    }else{
      app.mainTimeCallback = mainTime => {
        if (mainTime != '') {
          let dateType = 0
          for(let i in mainTime){
            let isDate = util.setDate(mainTime[i].food_time,mainTime[i].food_end_time)
            if(isDate){
              dateType = Number(mainTime[i].id)
              break;
            }
          }
          that.setData({
            mainTime: mainTime,
            dateType: Number(dateType)
          })
        }
      }
    }
    if(app.globalData.userId){
      that.setData({
        userId: app.globalData.userId
      })
    }else{
      app.userIdCallback = userId => {
        if (userId != '') {
          that.setData({
            userId: userId
          });
        }
      }
    }
    if(app.globalData.contentId){
      that.setData({
        contentId: app.globalData.contentId
      })
    }else{
      app.contentIdCallback = contentId => {
        if (contentId != '') {
          that.setData({
            contentId: contentId
          });
        }
      }
    }
    if(app.globalData.status){
      that.setData({
        status: app.globalData.status
      })
    }else{
      app.statusCallback = status => {
        if (status != '') {
          that.setData({
            status: status
          });
        }
      }
    }
    
  },
})